package org.mxp.demo4;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import org.mxp.utils.RabbitMQUtils;

import java.util.Date;

public class ReceiveObj1 {
    public static void main(String[] args) throws Exception {
        // 获取信道
        Channel channel = RabbitMQUtils.getChannel();
        // 获取当前时间，区分不同线程
        Date now = new Date();
        // 接收到消息回调
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody());
            System.out.println(now.getTime() + "，接受到消息：" + message);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            // 应答消息，第一个参数固定写法，获取tag，第二表示不批量
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            System.out.println(now.getTime() + "，处理完消息：" + message);
        };
        // 取消消息时回调
        CancelCallback cancelCallback = (consumerTag) -> {
            System.out.println("消息消费被中断");
        };
        // 设置不公平分发
        channel.basicQos(1);
        // 接受消息，并且手动应答
        channel.basicConsume("demo4", false, deliverCallback, cancelCallback);
    }
}
